package vn.demand.dragon.view
{
	import com.adobe.utils.StringUtil;
	
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.FocusEvent;
	
	import flexed.widgets.alerts.alert;
	
	import mx.core.Application;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import vn.demand.dragon.CommonCommand;
	import vn.demand.dragon.model.UserProxy;
	import vn.demand.dragon.view.components.LoginDialog;
	
	public class LoginDialogMediator extends Mediator
	{
		
		public static const NAME:String = "LoginDialogMediator";
		
		public static var application:Object = null;
		
		private var errorStrings:String = "";
		
		
		public function LoginDialogMediator(app:Object)
		{
			super(NAME);
			application = app;
		}

		public function get loginForm() : LoginDialog {
			return viewComponent as LoginDialog;
		}
		
		public function show():void {
			var popup:LoginDialog = PopUpManager.createPopUp(Application.application as DisplayObject, LoginDialog, true) as LoginDialog;
			setViewComponent(popup);
			loginForm.addEventListener("login", onLogin);
			PopUpManager.centerPopUp(popup);
		}
		
		public function onLogin(event:Event) {
			if (!doValidate()) {
				alert.error(errorStrings);
				return;
			}
			var userProxy : UserProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
			userProxy.login(loginForm.username.text, loginForm.password.text);
		}
		
		public function doValidate():Boolean {
			errorStrings = "";
			if (StringUtil.trim(loginForm.username.text).length == 0) {
				errorStrings += "Please input [Username]\n";
			}
			if (StringUtil.trim(loginForm.password.text).length == 0) {
				errorStrings += "Please input [Password]\n";
			}
			return errorStrings.length == 0	? true : false;
		}
		
		override public function listNotificationInterests():Array 
        {
            return [ 
            	CommonCommand.LOGIN_FAILED,
            	CommonCommand.LOGIN_SUCCESSFUL
					 ];
        }
        
        override public function handleNotification( note:INotification ):void 
        {
            switch ( note.getName() ) 
			{
				case CommonCommand.LOGIN_FAILED:
					errorStrings = note.getBody() as String;
					alert.error(errorStrings);
					break;
				case CommonCommand.LOGIN_SUCCESSFUL:
					PopUpManager.removePopUp(loginForm);
                default:
                	break;
            }
        }
	}
}